﻿function AppBase(tagId, appPages, hostControllers)
{
	AppBase.$baseConstructor.call(this);

	this.tagId = tagId;
	this.config = new Config();
	this.nav = new NavigationController(this, hostControllers);
	this.contexts = [];
	this.controllers = [this.nav];
	this.appPages = appPages;

	if (AppBase.instance)
	{
		this.log.warn('More than one instance of AppBase detected.');
	}
	AppBase.instance = this;

	var $this = this;
	JSN.onSuccess = function(args)
	{
		$this.dispatchEvent("onGatewaySuccess", $this, args);
	};
	JSN.onError = function(args)
	{
		$this.dispatchEvent("onGatewayError", $this, args);
	};
}
p = AppBase.extend(ASObject, { type: 'AjaxStack.AppBase' });
AppBase.getInstance = function()
{
	return AppBase.instance;
}
AppBase.getNav = function()
{
	return AppBase.getInstance().getNav();
}
AppBase.getAppPages = function()
{
	return AppBase.getInstance().getAppPages();
}
AppBase.getPage = function(pageName, args)
{
	return AppBase.getInstance().getPage(pageName, args);
}

p.getTagId = function() { return this.tagId; }
p.getNav = function() { return this.nav; }
p.getConfig = function() { return this.config; }
p.getAppPages = function() { return this.appPages; }
p.getPage = function(pageName, args) { return this.appPages.pages[pageName](args); }
p.getContexts = function() { return this.contexts; }
p.getControllers = function()
{
	var all = [];
	for (var i = 0, len = this.controllers.length; i < len; i++)
	{
		var c = this.controllers[i];
		all.push(c);
		A.merge(all, c.getControllers());
	}
	return all;
}

p.navigateTo = function(path)
{
	var $this = this;
	$(function()
	{
		$this.nav.loadPath(path);
	});
}

//dispatch an event to all contexts and controllers
p.dispatchEvent = function(eventName, source, args)
{
	var allContexts = this.getContexts();
	var allControllers = this.getControllers();

	this.log.debug("dispatchEvent: '" + eventName + "' to " + allContexts.length + " Contexts and " + allControllers.length + " controllers");

	for (var i = 0, len = allContexts.length; i < len; i++)
	{
		this.fireEvent(allContexts[i], eventName, source, args);
	}

	for (var i = 0, len = allControllers.length; i < len; i++)
	{
		this.fireEvent(allControllers[i], eventName, source, args);
	}
}

p.fireEvent = function(target, eventName, source, args)
{
	if (target[eventName])
	{
		this.log.debug("fireEvent(): " + eventName + " on " + target);
		target[eventName](source, args);
	}
};


